package top.dtyy.concurrent.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 计数
 *
 * @author lzp
 * @version v1.0 at 2018/11/26
 */
public class CountExample {
    /**
     * 允许200个请求同时执行
     */
    private static int threadTotal = 2;
    /**
     * 模拟系统短时间内接收到5000个请求
     */
    private static int clientTotal = 5000;

    private static long count = 0;

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        for (int index = 0; index < clientTotal; index++) {
            exec.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
//                    log.error("exception", e);
                }
            });
        }
        exec.shutdown();
//        log.info("count:{}".count);
        System.out.println(count);
    }

    private static void add() {
        count++;
    }
}
